<?php
namespace app\admin\controller;

use think\Controller;

use app\model\Admin as AdminModel;
class Admin extends Allow
{
    /**
     * 列表
     * 
     * @return \think\response\View
     * @throws \think\Exception\DbException
     */
    public function index()
    {
        $data = AdminModel::order("id desc")->all();
        $this->assign(['data' => $data,'total' => count($data)]);
        return view('index');
    }

    /**
     * 添加
     * @return \think\response\View
     */
    public function add()
    {
        return view("add");
    }

    /**
     * 修改
     * @return \think\response\View
     */
    public function edit()
    {
        $id = input("id");
        $data = AdminModel::find($id);
        $this->assign(['data' => $data]);
        return view("edit");
    }

    /**
     * 执行 添加修改
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function executeData()
    {
       $param = request()->param();
       if(empty($param['id'])) {
           $admin = AdminModel::where('account',$param['account'])->find();
           if(!empty($admin)) errorMsg("该账号已经存在");
       }
       $data = AdminModel::executeData($param);
       if($data) return successMsg("成功");
       return errorMsg("失败");
    }

    /**
     * 状态修改
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function editStatus()
    {
        $obj =  new AdminModel();
        $id = input("id");
        $data = $obj->where('id',$id)->find();
        $state = $data['state'] == 0 ? 1 : 0;
        $obj->save(['state' => $state],['id' => $id]);
    }

    /**
     * 删除数据
     *
     * @return array
     */
    public function delete()
    {
        $id = input("id");
        $del = AdminModel::destroy($id);
        if($del) return successMsg("删除成功");
        return errorMsg("删除失败");
    }
}